package com.zyht.website.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wx.entity.SysWebArticle;
import com.wx.model.BussinessException;
import com.wx.model.article.SiteModel;
import com.wx.service.ArticlemsgService;
import com.wx.service.SaveArticleParameter;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.util.Page;

/**
 * 
 * 文章管理
 * 
 * @author dingyaming
 *
 */
@Controller
@RequestMapping("admin/articlemsg")
public class ArticlemsgAdminController extends AbsManageBaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private ArticlemsgService articleService;

	@RequestMapping("index")
	public String index(Integer currentPage, Long siteid, String search, Model model) {
		if (currentPage == null) {
			currentPage = 1;
		}

		Page<SysWebArticle> page = articleService.getListByPage(currentPage, siteid);
		List<SiteModel> siteAll = articleService.getSite();
		model.addAttribute("siteAll", siteAll);
		model.addAttribute("siteid", siteid);
		model.addAttribute("page", page);
		model.addAttribute("search", search);

		return "admin/article/index";
	}

	@RequestMapping("saveview")
	public String saveview(Model model, Long article_id) {
		List<SiteModel> listSite = articleService.getSite();
		if (listSite == null || listSite.isEmpty()) {
			return message("栏目编号未设置", "manage/articlemsg/index", model);
		}
		model.addAttribute("listSite", listSite);
		if (article_id == null) {
			model.addAttribute("article", new SysWebArticle());
		} else {
			SysWebArticle article = articleService.getArticle(article_id);
			if (article == null) {
				return message("未知文章", "manage/articlemsg/index", model);
			}
			model.addAttribute("article", article);
		}
		return "admin/article/saveview";
	}

	@RequestMapping("save")
	@ResponseBody
	public String save(SaveArticleParameter bean) throws Exception {
		if (bean.getSite_id() == null) {
			throw new BussinessException("栏目编号不正确");
		}

		if (bean.getName() == null) {
			throw new BussinessException("文章标题不正确");
		}

		if (bean.getPublish() == null) {
			throw new BussinessException("发布时间不正确");
		}

		if (bean.getContent() == null) {
			throw new BussinessException("正文不正确");
		}

		//Long article_id = bean.getSite_id();
		Long article_id = bean.getArticle_id();
		if (article_id == null) {
			
		} else {
			SysWebArticle al = articleService.getArticle(article_id);
			
			if (al == null) {
				throw new BussinessException("文章编号不正确");
			}
		}
		articleService.doSaveArticle(bean, article_id);
		return JsonUtil.Object2Json(JsonResult.messageJson(true, ""));
	}

	@RequestMapping("del/{id}/{currentPage}")
	public String removeArtilcleById(@PathVariable("id") Integer id, @PathVariable("currentPage") Integer currentPage,
			HttpSession session) {
		if (null != id) {
			try {
				String rootPath = session.getServletContext().getRealPath("");
				SysWebArticle article = articleService.getArticle(Long.valueOf(id));
				String content = article.getContent();
				List<String> imgStr = getImgStr(content);
				for (String img : imgStr) {
					String[] split = img.split("upload");
					String realPath = rootPath.concat("/upload").concat(split[1]);
					File file = new File(realPath);
					if (file.exists()) {
						file.delete();
					}
				}
			} catch (Exception e) {
				logger.error("删除文章图片：" + e.getMessage());
			}
			this.articleService.deleteArticleById(Long.valueOf(id));
		}
		return "redirect:/admin/articlemsg/index?currentPage=" + currentPage.intValue();
	}

	private List<String> getImgStr(String htmlStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();
		String regEx_img = "<img.*src=(.*?)[^>]*?>"; // 图片链接地址
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(htmlStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img);// 匹配src
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	private String message(String msg, String redirect, Model model) {
		model.addAttribute("msg", msg);
		model.addAttribute("redirect", redirect);
		return "message";
	}
}
